package examples.complex.view.personlogin

import de.saxsys.mvvmfx.FxmlView
import de.saxsys.mvvmfx.InjectViewModel
import examples.complex.viewmodel.personlogin.PersonLoginViewModel
import examples.complex.viewmodel.personlogin.PersonLoginViewModelNotifications
import javafx.beans.value.ChangeListener
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Alert
import javafx.scene.control.Button
import javafx.scene.control.ChoiceBox
import javafx.scene.control.ProgressIndicator

/**
 * Created by Misty on 2015/6/6.
 */
class PersonLoginView implements FxmlView<PersonLoginViewModel>, Initializable {
    @FXML
    private ChoiceBox<String> personsChoiceBox

    @FXML
    private Button loginButton

    @FXML
    private ProgressIndicator loginProgressIndicator

    @InjectViewModel
    private PersonLoginViewModel viewModel

    @Override
    void initialize(URL location, ResourceBundle resources) {
        initChoiceBox()

        loginButton.disableProperty().bind(viewModel.loginCommand.notExecutableProperty())
        loginProgressIndicator.visibleProperty().bind(viewModel.loginCommand.runningProperty())

        viewModel.subscribe(PersonLoginViewModelNotifications.OK.id, { key, payload ->
            def message = payload[0] as String
            new Alert(Alert.AlertType.INFORMATION).with {
                it.title = message
                it.contentText = message
                it.show()
            }
        })
    }

    void loginButtonPressed(final ActionEvent event) {
        viewModel.loginCommand.execute()
    }

    private void initChoiceBox() {
        personsChoiceBox.itemsProperty().bind(
                viewModel.selectablePersonsProperty().stringListProperty()
        )
        personsChoiceBox.selectionModel
                .selectedIndexProperty()
                .addListener({ obs, oval, nval ->
            viewModel.selectablePersonsProperty().select(nval.intValue())
        } as ChangeListener)
    }

    PersonLoginViewModel getViewModel() {
        return viewModel
    }
}
